//
//  ZZTongAutoCompleteView.m
//  HPZZTong
//
//  Created by xy on 14-04-12.
//  Copyright (c) 2014年 __MyCompanyName__. All rights reserved.
//

#import "ZZTongAutoCompleteViewV2.h"
#import <QuartzCore/QuartzCore.h>
#import "DefineUtil.h"
#import "HPUIEngine.h"
#import "HPAbstrictViewController.h"
#import "HPConditionTextField.h"

// 最大显示充值记录条数
static int MaxSize = INT32_MAX;

@interface ZZTongAutoCompleteViewV2(){
    int showCount;
    int tableWidth;
    BOOL isEndChanged;
}


// 自动提示table view
@property (nonatomic, retain) UITableView *autoCompleteTableView;

@property (nonatomic, retain) NSArray *searchArray;
@property (nonatomic, retain) NSString *lastSearchWord;

@property (nonatomic, retain) UITextField *showTextFiled;
@property (nonatomic, retain) UIView *contentView;
@end

@implementation ZZTongAutoCompleteViewV2

#define CONTENT_X_OFFSET  50
#define CONTENT_Y_OFFSET  20

- (void)setTableWidth:(int)width{
    tableWidth = width;
}

- (void)setHint:(NSString*)hint{
    self.showTextFiled.placeholder = hint;
    self.contentTextField.placeholder = hint;
}

-(void)initViewStyle{
    [[self superview] bringSubviewToFront:self];
    isEndChanged = NO;
    
    UITextField *textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    textFiled.delegate = self;
    textFiled.textColor = kTitleFontColor;
    textFiled.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.showTextFiled = textFiled;
    [textFiled release];
    [self addSubview:self.showTextFiled];
    
    UIView *tempContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    tempContentView.backgroundColor = RGBACOLOR(0, 0, 0, 0.8);
    self.contentView = tempContentView;
    [tempContentView release];
    
    CGRect contentFrame = CGRectMake(0, CONTENT_Y_OFFSET, ScreenWidth, ScreenHeight - IOS7_VIEW_FRAME_Y - CONTENT_Y_OFFSET);
    UIView *bgView = [[UIView alloc] initWithFrame:contentFrame];
    bgView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:bgView];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, CGRectGetWidth(contentFrame) - CONTENT_X_OFFSET - 10, 41)];
    imageView.image = [[UIImage imageNamed:@"input_bg"] stretchableImageWithLeftCapWidth:7 topCapHeight:0];
    [bgView addSubview:imageView];
    [imageView release];
    
    
    HPConditionTextField* tempTextField = [[HPConditionTextField alloc] initWithFrame:CGRectMake(20, 0, CGRectGetWidth(imageView.frame) - 20, 41)];
    tempTextField.textColor = kTitleFontColor;
    tempTextField.returnKeyType = UIReturnKeyDone;
    tempTextField.conditionType = HPConditionType_Deafult;
    tempTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.contentTextField = tempTextField;
    [tempTextField release];
    [bgView addSubview:self.contentTextField];
    
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    cancelButton.frame = CGRectMake(CGRectGetMaxX(imageView.frame), 0, CONTENT_X_OFFSET, 41);
    [cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cancelButton];
    [self.contentTextField setDelegate:self];
    
    UITableView* tempTableView  = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tempTableView.frame = CGRectMake(0, CGRectGetMaxY(imageView.frame), CGRectGetWidth(contentFrame), CGRectGetHeight(bgView.frame) - CGRectGetMaxY(imageView.frame));
    self.autoCompleteTableView = tempTableView;
    [tempTableView release];
    
    [self.autoCompleteTableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    [self.autoCompleteTableView setDataSource:self];
    [self.autoCompleteTableView setDelegate:self];
    [bgView addSubview:self.autoCompleteTableView];
    
    [bgView release];
    
    [NOTIFICATION addObserver:self selector:@selector(textChanged:) name:UITextFieldTextDidChangeNotification object:self.contentTextField];
     [NOTIFICATION addObserver:self selector:@selector(popToLoginScreen:) name:WillPopToLoginNotificationKey object:nil];
    
}
- (void)popToLoginScreen:(NSNotification*)notification{
    [self hideContentView];
}
- (void)cancelButtonClick:(UIButton*)button{
    [self hideContentView];
}

//重置历史充值记录
- (void)changeSearchArray:(NSArray *)data{
    self.searchArray = data;
    
    if (!self.searchArray || (self.searchArray.count == 0)) {
        showCount = 0;
        [self.autoCompleteTableView reloadData];
        return;
    }
    
    showCount = self.searchArray.count;
    if (MaxSize != INT32_MAX) {
        showCount = showCount < MaxSize ? showCount : MaxSize;
    }

    [self.autoCompleteTableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if ([self.autoCompleteTableView superview]) {
        [self.autoCompleteTableView removeFromSuperview];
    }
    
    self.lastSearchWord = nil;
    self.contentTextField = nil;
    self.autoCompleteTableView = nil;
    self.searchArray = nil;
    
    self.showTextFiled = nil;
    self.contentView = nil;
    
    self.delegate = nil;
    
    [super dealloc];
}

- (void)showContentView{
    UIView* superView = [self.contentView superview];
    if (superView) {
        [superView removeFromSuperview];
    }
    
//    UIWindow* window = [UIApplication sharedApplication].keyWindow;
//    [window addSubview:self.contentView];
    HPAbstrictViewController* screen = (HPAbstrictViewController*)[HPUIENG getCurrentScreen];
    [screen.view addSubview:self.contentView];
    screen.backButton.enabled = NO;
    [self.contentTextField becomeFirstResponder];
}

- (void)hideContentView{
    HPAbstrictViewController* screen = (HPAbstrictViewController*)[HPUIENG getCurrentScreen];
    screen.backButton.enabled = YES;
    [self.contentView removeFromSuperview];
}

- (void) setKeboardType:(UIKeyboardType) type{
    self.contentTextField.keyboardType = type;
}

#pragma mark - table view datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return showCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* identifier = @"autoCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        [cell.textLabel setBackgroundColor:[UIColor clearColor]];
        [cell.textLabel setFont:kNormalFont];
        [cell.textLabel setTextColor:kNormalFontColor];
        [cell.textLabel setTextAlignment:NSTextAlignmentCenter];
    }
    if (self.searchArray && (self.searchArray.count > indexPath.row)) {
        [cell.textLabel setText:[self.searchArray objectAtIndex:indexPath.row]];

    }
    
    return cell;
}

#pragma mark - table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    isEndChanged = YES;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *cellStr = [tableView cellForRowAtIndexPath:indexPath].textLabel.text;
    [self.showTextFiled setText:cellStr];
    [self hideContentView];
}


#pragma mark - text field delegate

- (void)textChanged:(NSNotification*)no{
    if (!self.delegate) {
        return;
    }
    
    if (isEndChanged) {
        return;
    }
    
    UITextField* textField = no.object;
    if (![textField isFirstResponder]) {
        return;
    }
    
    UITextRange *selectedRange = [textField markedTextRange];
    NSString * newText = [textField textInRange:selectedRange];
    
    if ([NSString isNilOrEmpty:newText]) {
        if (!textField.text) {
			self.lastSearchWord = nil;
            return;
        }
        if ([self.lastSearchWord isEqualToString:textField.text]) {
            return;
        }
        self.lastSearchWord = textField.text;
        [self.delegate searchWordChanged:self word:textField.text];
    }
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    if ([textField isEqual:self.showTextFiled]) {
        [self showContentView];
        return NO;
    }
    
    isEndChanged = NO;
    self.lastSearchWord = textField.text;
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void) textFieldDidEndEditing:(UITextField *)textField
{

}

//读取text属性
- (NSString*)readText{
    return self.showTextFiled.text;
}

- (void)setText:(NSString *)text{
    self.showTextFiled.text = text;
    self.contentTextField.text = text;
    [self changeSearchArray:nil];
}

@end
